const service = require('../../utils/service.js')
const api = require('../../utils/util.js')
Page({
  data: {
    shopInfo: {},
    goodsList: [],
    category_id: '',
    page: 1,
    hasMoreData: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let category_id = options.category_id
    this.setData({
      category_id: category_id
    })
    let shopInfo = wx.getStorageSync('shopInfo')
    this.setData({
      shopInfo: shopInfo
    })
    this.getGoodsList()
  },

  // 获取商品列表
  getGoodsList: function () {
    let that = this
    api.ajax(service.url('goodsSearch'), {
      unionid: that.data.shopInfo.unionid,
      token: wx.getStorageSync('shop_data').token,
      token_key: wx.getStorageSync('shop_data').token_key,
      shop_code: that.data.shopInfo.shop_code,
      page: that.data.page,
      category_id: that.data.category_id
    }, function (res) {
      if (res.code == 0) {
        if (res.data.length > 0) {
          res.data.forEach(function(item, index) {
            that.data.goodsList.push(item)
          })
          that.setData({
            hasMoreData: true,
            goodsList: that.data.goodsList
          })
        } else {
          that.setData({
            hasMoreData: false
          })
        }
      } else {
        api.toast(res.message)
      }
    })
  },

  // 前往商品详情
  toGoodsDetail: function (e) {
    var goods_id = e.currentTarget.dataset.id
    if (!goods_id) {
      return
    }

    var yzc = e.currentTarget.dataset.yzc
    var audit = e.currentTarget.dataset.audit

    let url = `../goods_detail/goods_detail?goods_id=${goods_id}`
    if (yzc && audit == '1') {
      url = `../goods_detail/goods_detail?goods_id=${goods_id}&is_yzc=${yzc}`
    }
    wx.navigateTo({
      url: url,
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let page = this.data.page += 1
    if (this.data.hasMoreData) {
      this.setData({
        page: page
      })
      this.getGoodsList()
    } else {
      api.toast('没有更多数据了')
    }
  }
})